package com.paradogs.framework.core.netty.clients.common;

import com.paradogs.framework.core.events.ServerClientStartEvent;
import com.paradogs.framework.core.netty.clients.PRClientChannelInitializer;
import com.paradogs.framework.core.utils.EventUtils;
import com.paradogs.framework.core.utils.SpringUtils;
import com.paradogs.framework.core.utils.StringUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: yumi
 * @date: 2023/7/31  22:36
 * @Description: 用于连接 master 服务器
 */
@Slf4j
public class PRServerClient {

    private ClientsProperties.Client properties;

    private PRClientChannelInitializer clientChannelInitializer;

    private Bootstrap client;

    private NioEventLoopGroup worker;

    private Channel channel;

    public PRServerClient(ClientsProperties.Client properties) {
        this.properties = properties;
        this.clientChannelInitializer = SpringUtils.getBean(PRServerClientChannelInitializer.class, new PRServerClientMsgHandler(properties));
    }

    /**
     * 连服服务器
     */
    public void start() {

        try {
            // eventLoop
            worker = new NioEventLoopGroup();

            // init
            this.client = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(clientChannelInitializer);

            // connect
            channel = client.connect(properties.getHost(), properties.getPort()).sync().channel();
            EventUtils.publishEvent(new ServerClientStartEvent());

        } catch (Exception e) {
            log.error("Client connect error：{}", e.getMessage(), e);
        }

    }

}
